package com.zeta.auth.common.config;

import cn.dev33.satoken.stp.StpInterface;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.zeta.auth.dao.UserInfoMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import org.zetaframework.core.constants.RedisKeyConstants;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 权限数据源加载接口 实现类
 *
 * @author gcc
 */
@Component
@RequiredArgsConstructor
public class StpInterfaceImpl implements StpInterface {

    private final UserInfoMapper userInfoMapper;

    /**
     * 返回指定账号id所拥有的权限码集合
     *
     * @param loginId   账号id
     * @param loginType 账号类型
     * @return 该账号id具有的权限码集合
     */
    @Cacheable(value = RedisKeyConstants.USER_PERMISSION_KEY, key = "#p0", unless = "#result.isEmpty()")
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        if (ObjectUtil.isNull(loginId)) { return Collections.emptyList(); }

        // 根据用户ID获取权限列表
        List<String> authorities = userInfoMapper.listPermissionByUserId(Long.parseLong(loginId.toString()));
        if (CollUtil.isEmpty(authorities)) { return Collections.emptyList(); }

        // 筛选出 authority 不为空的数据
        return authorities.stream().filter(StrUtil::isNotBlank).toList();
    }

    /**
     * 返回指定账号id所拥有的角色标识集合
     *
     * @param loginId   账号id
     * @param loginType 账号类型
     * @return 该账号id具有的角色标识集合
     */
    @Cacheable(value = RedisKeyConstants.USER_ROLE_KEY, key = "#p0", unless = "#result.isEmpty()")
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        if (ObjectUtil.isNull(loginId)) { return Collections.emptyList(); }

        // 根据用户ID获取角色列表
        List<String> roles = userInfoMapper.listRoleByUserId(Long.parseLong(loginId.toString()));
        if (CollUtil.isEmpty(roles)) { return Collections.emptyList(); }

        // 筛选出 roles 不为空的数据
        return roles.stream()
                .filter(StrUtil::isNotBlank)
                .collect(Collectors.toList());
    }
}
